﻿using UnityEngine;
using UnityEngine.UI;
using System;
using BestHTTP;
using LitJson;
using System.Text;
using System.Collections;
using UnityEngine.Networking;

//ilab登录
public class StartPanel : MonoBehaviour
{
    public Button StartBtn;
    public GameObject loginPanel;
    public GameObject mainPanel;

    private void Start()
    {
        GetIPFromStreamingAssets();
        //判断是否为ilab平台（有token：是）
        StartBtn.onClick.AddListener(() =>
        {
            if (String.IsNullOrEmpty(GetURLInfo.UrlMsg))
            {
                Debug.Log("UrlMsg is null");
                OnClickCallBack(false);
            }
            else
            {
                Debug.Log("UrlMsg:" + GetURLInfo.UrlMsg);
                OnClickCallBack(true);
            }
        });
    }
    private void OnClickCallBack(bool haveToken)
    {
        //如果有token，跳过登陆,token值为id
        if (haveToken)
        {
            TokenRequest();
        }
        else
        {
            CreatePanel(loginPanel);
        }
    }

    private void TokenRequest()
    {
        HTTPRequest request = new HTTPRequest(new Uri(UserSingleton.ILabTokenUrl), HTTPMethods.Post, TokenResponse);
        // request.AddField("token",  GetURLInfo.UrlMsg.Substring(1).Split('=')[1]
        // //"AAABasPH5UgBAAAAAAABh4I%3D.556I05R8RbRWDKTiaCLlmxds9tJ8wz%2BAWDBGsKdGg5fPBnc7DhloIc3P%2Ff2LHVGJ.mZ3NxYxl0Y5g1TesDzqKEQx9roXOaqONfDJ0oCikFtY%3D"
        // );
        request.RemoveHeaders();
        request.SetHeader("Content-Type", "application/json; charset=UTF-8");

        string jsonString = MsgToJson();
        request.RawData = Encoding.UTF8.GetBytes(jsonString);
        request.Send();
    }

    private void TokenResponse(HTTPRequest request, HTTPResponse response)
    {
        int responseState = response.StatusCode;
        print("responseState:" + responseState);

        if (responseState == 200)
        {
            JsonData jd = JsonMapper.ToObject(response.DataAsText);
            UserSingleton.ID = jd["un"].ToString();
            UserSingleton.showName = "用户名（ilab-x.com）：" + jd["dis"].ToString();
            //jd["id"];
            //jd["un"];
            Debug.Log("response.DataAsText: " + response.DataAsText);
            print("发送成功");
            //todo
            CreatePanel(mainPanel);
        }
        else
        {
            CreatePanel(loginPanel);
            print("发送失败");
        }
    }

    private string MsgToJson()
    {
        JsonData data = new JsonData();
        //GetURLInfo.UrlMsg
        //?token=AAABasTkVFYBAAAAAAABh4I%3D.fem%2Fv%2FHKfo2ZvwKfdM6Lpa2DLYfoBGBYqH3Tkyw5IMDBUsiY1gWGBPd0z4UChjFW.AExETcQOyaVzK1%2B21vmbgvM6FHbQNiFjJCoky0rRykI%3D

        data["token"] = GetURLInfo.UrlToken;
        data["issuerId"] = UserSingleton.IssuerId;

        return data.ToJson();
    }

    /// <summary>
    /// 在streamingassets下读取文件找到IP
    /// </summary>
    private void GetIPFromStreamingAssets()
    {
        string path = Application.streamingAssetsPath + "/path.json";
        StartCoroutine(GetIP(path));
    }

    /// <summary>
    /// 外部读取ip
    /// </summary>
    /// <param name="a"></param>
    /// <returns></returns>
    private IEnumerator GetIP(string path)
    {
        UnityWebRequest req = UnityWebRequest.Get(path);
        yield return req.SendWebRequest();
        print("path:" + path);
        if (req.isNetworkError || req.isHttpError)
        {
            Debug.LogError("read StreamingAssets file error：" + req.error);
        }
        else
        {
            //url配置文件
            JsonData jd = JsonMapper.ToObject(req.downloadHandler.text);
            //ilab后台
            UserSingleton.ILabTokenUrl = jd["ILabTokenUrl"].ToString();
            UserSingleton.ILabStatusUrl = jd["ILabStatusUrl"].ToString();
            UserSingleton.ILabStudentMsgUrl = jd["ILabStudentMsgUrl"].ToString();
            //自建后台
            UserSingleton.StudentMsgUrl = jd["StudentMsgUrl"].ToString();
            UserSingleton.StudentLoginUrl = jd["StudentLoginUrl"].ToString();
            UserSingleton.StudentRegisterUrl = jd["StudentRegisterUrl"].ToString();
            UserSingleton.StudentRegisterNameUrl = jd["StudentRegisterNameUrl"].ToString();
        }
    }

    private void CreatePanel(GameObject gameObject)
    {
        GameObject obj = Instantiate(gameObject);
        obj.SetActive(true);
        obj.transform.position = Vector3.zero;
        Destroy(this.gameObject);
    }
}

